Thumb

What is Serializing?

1/12/2020 6:43:20 AM

Serializing: In C# serialization is the process of converting object into byte stream so that it can be saved to memory, file or database. The reverse process of serialization is called deserialization. Serialization is used in remote applications. Now given bellow the example code and explain the code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
using testForClass1;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace testFor
{
    [Serializable]
    public class Student
    {
       public int Id;
       public string Name;
        public Student(int id,string name)
        {
            this.Id = id;
            this.Name = name;
        }
    }
    public class Program
    {
        static void Main(string[] args)
        {
            string path= @"F:\jesy.txt";
            Student std = new Student(1, "Jesy");
            FileStream sw = new FileStream(path, FileMode.OpenOrCreate);
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(sw,std);
            sw.Close();
            Console.ForegroundColor =  System.ConsoleColor.Red;
            Console.WriteLine("File Saved",path);
            FileStream st = new FileStream(path, FileMode.OpenOrCreate);
            Student s = (Student)formatter.Deserialize(st);
            Console.ForegroundColor = System.ConsoleColor.Green;
            Console.WriteLine("Deserialize file");
            Console.WriteLine("Student ID : " +s.Id);
            Console.WriteLine("Student Name : "+s.Name);
            Console.Read();
        }
    }
}

In this code we create a student class under the class we have write two property names as “Id” and “Name”. This property initializes by the constructor then we create FileStream object and take path to create file for save student object binary data. Then close the FileStream. Now we write some code get the data in the same location and Deserialize the data also show the console.